from apps.goods.models import SKUImage,SKU
from rest_framework import serializers

class ImageSerializer(serializers.ModelSerializer):

    class Meta:
        model = SKUImage
        fields = '__all__'

    # 更新图片方法二，代码更少
    def update(self, instance, validated_data):

        from fdfs_client.client import Fdfs_client
        client = Fdfs_client('utils/fastdfs/client.conf')
        upload_image = validated_data.get('image')
        result = client.upload_by_buffer(upload_image.read())
        if result['Status']!= 'Upload successed.':
            raise serializers.ValidationError('图片上传失败')
            #序列化器中不能响应，应抛出异常
        fild_id = result['Remote file_id']
        #put请求时通过路径参数pk,已找到实例对象instance修改图片地址即可
        instance.image = fild_id
        instance.save()
        return instance  #必须返回instance

class SKUSerializer(serializers.ModelSerializer):

    class Meta:
        model = SKU
        fields = ['id','name']